---
import shop from "@/assets/formula/credit_shop.png";
import SingleItem from "./components/SingleItem.astro";
import type { CreditShop } from "@/types/formula";
import useIcon from "@/hooks/useIcon";
import { Image } from "astro:assets";
import { AstroError } from "astro/errors";

export interface Props {
  formula: CreditShop;
  alt?: string;
}

const {
  formula: { result, useItem: useItem, ingredients, credit },
  alt = "积分商店兑换",
} = Astro.props;

const normalPoint = useIcon("providencraft:pdc_point");
const premiumPoint = useIcon("providencraft:premium_pdc_point");

const itemIcons = ingredients?.slice(0, 2).map((i) => useIcon(i.item)!);
if (useItem && (itemIcons?.length ?? 0) <= 0) {
  throw new AstroError(`物品兑换至少需要一个物品!`);
}

const resultIcon = useIcon(result.item)!;
if (!resultIcon) throw new AstroError(`找不到以下物品图标: ${result}`);

const firstItemIcon = useItem
  ? itemIcons?.[0]
  : (credit as number) > 64
  ? premiumPoint
  : normalPoint;

const firstItemCount = useItem
  ? ingredients?.[0]?.count
  : (credit as number) > 64
  ? Math.floor((credit as number) / 64)
  : credit;

const hasSecondItem = useItem
  ? itemIcons?.[1]
  : (credit as number) > 64 && (credit as number) % 64 > 0;

const secondItemIcon = useItem
  ? itemIcons?.[1]
  : (credit as number) > 4096
  ? premiumPoint
  : normalPoint;
const secondItemCount = useItem
  ? ingredients?.[1]?.count
  : (credit as number) > 4096
  ? Math.floor((credit as number) / 4096)
  : (credit as number) % 64;
---

<div class="relative mb-1 w-80 h-[180px] origin-top-left md:scale-100 scale-90">
  <Image src={shop} alt={alt} class="!bg-transparent" />
  <div class="absolute top-[63px] left-[59px]">
    <SingleItem
      src={firstItemIcon!.smallIcon}
      title={firstItemIcon!.name}
      id={firstItemIcon!.registerName}
      count={firstItemCount}
    />
  </div>
  {
    hasSecondItem && (
      <div class="absolute top-[63px] left-[110px]">
        <SingleItem
          src={secondItemIcon!.smallIcon}
          title={secondItemIcon!.name}
          id={secondItemIcon!.registerName}
          count={secondItemCount}
        />
      </div>
    )
  }
  <div class="absolute top-[63px] left-[226px]">
    <SingleItem
      src={resultIcon.smallIcon}
      title={resultIcon.name}
      count={result.count}
    />
  </div>
</div>
